<?php
namespace api\utils;
use herosphp\core\Loader;
use herosphp\core\Log;
use herosphp\core\WebApplication;
use herosphp\http\HttpClient;
use herosphp\string\StringUtils;
use herosphp\utils\AjaxResult;
use rsa\RSACrypt;
use rsa\SignUtil;

/**
 * api通用客户端
 * @author yangjian<yangjian102621@gmail.com>
 */
class SaasApiClient {

    /**
     * 发送api调用请求
     * @param $uri
     * @param $params
     * @return AjaxResult
     */
    public static function send($uri, $params) {

        $domain = getConfig('saas_api_url');
        $client = new HttpClient();
        //$url = self::DOMAIN.$uri;
        $url = $domain.$uri;
        $params['__timer'] = time()+100;
        $params['__appid'] = appId();
        //build headers
        $headers = array('appName' => 'offer');
        $tokens = Loader::config('token');
        $headers['token'] = $tokens[$headers['appName']];

        $sign = SignUtil::sign($url, $params);
        $rsa = new RSACrypt();
        $params['__sign'] = $rsa->encryptByPublicKey($sign);
        //签名错误时，可查看下面的注释内容，跟SaaS的日志比较，观察错误的参数
        Log::info($params);
        try {
            $result = $client->post($url, $params, $headers);
        }catch (\Exception $e){
            Log::error($e);
            return AjaxResult::fail($e->getMessage());
        }
        if( !is_json($result)){
            Log::error("APIReturnNotJsonException:".$result);
        }
        $result = StringUtils::jsonDecode($result);
        return new AjaxResult($result['code'], $result['message'], $result['data']);
    }
}
